﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using System.IO;
using System.ServiceProcess;

namespace NotifyServices
{
    public class ConfigService
    {
        public string ServiceName { get; set; }
        public int Order { get; set; }
        public int GroupBy { get; set; }
    }

    public class ExistingServices: List<ServiceController> 
    {
        public static List<string> GetAllExistingServicesNames()
        {
            return (from s in ServiceController.GetServices()
                    select s.ServiceName).ToList<string>();
        }
        public static List<ServiceController> GetServices(ServiceList Existing)
        {
            return (from s in ServiceController.GetServices()
                    where !(from e in Existing
                            select e.ServiceName).Contains<string>(s.ServiceName)
                    select s).ToList<ServiceController>();
        }
    }
    public class ServiceList : List<ConfigService>
    {
        public void Load()
        {
            XElement config = XElement.Load("Config.xml");
            this.AddRange(
                from service in config.Descendants("services").Elements("service")
                select new ConfigService()
                {
                    ServiceName = service.Value,
                    GroupBy = int.Parse(service.Attribute("group").Value),
                    Order = int.Parse(service.Attribute("order").Value)
                });
        }
        public void Save()
        {
            //bool result = false;
            XElement config = XElement.Load(Directory.GetCurrentDirectory() + @"\Config.xml");
            XElement services = config.Element("services");

            config.Element("services").ReplaceWith( 
                new XElement(
                "services",
                (from s in this
                 select new XElement(
                     "service",
                     s.ServiceName,
                     new XAttribute("order",s.Order),
                     new XAttribute("group",s.GroupBy)
                     )
                 ).ToList<XElement>()
                 )
            );

            config.Save(Directory.GetCurrentDirectory() + @"\Config.xml");
        }
    }
}
